from flask import Flask, render_template, request, jsonify, redirect, url_for
import sqlite3
import json
from datetime import datetime
import os

app = Flask(__name__)

# 初始化数据库
def init_db():
    conn = sqlite3.connect('letters.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS letters
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  title TEXT NOT NULL,
                  content TEXT NOT NULL,
                  is_public BOOLEAN DEFAULT 0,
                  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                  author TEXT DEFAULT '匿名')''')
    conn.commit()
    conn.close()

# 首页
@app.route('/')
def index():
    conn = sqlite3.connect('letters.db')
    c = conn.cursor()
    c.execute('SELECT * FROM letters WHERE is_public = 1 ORDER BY created_at DESC')
    public_letters = c.fetchall()
    conn.close()
    return render_template('index.html', letters=public_letters)

# 写信页面
@app.route('/write')
def write():
    return render_template('write.html')

# 保存信件
@app.route('/save_letter', methods=['POST'])
def save_letter():
    data = request.json
    title = data.get('title')
    content = data.get('content')
    is_public = data.get('is_public', False)
    
    conn = sqlite3.connect('letters.db')
    c = conn.cursor()
    c.execute('INSERT INTO letters (title, content, is_public) VALUES (?, ?, ?)',
              (title, content, is_public))
    conn.commit()
    letter_id = c.lastrowid
    conn.close()
    
    return jsonify({'success': True, 'letter_id': letter_id})

# 查看信件
@app.route('/letter/<int:letter_id>')
def view_letter(letter_id):
    conn = sqlite3.connect('letters.db')
    c = conn.cursor()
    c.execute('SELECT * FROM letters WHERE id = ?', (letter_id,))
    letter = c.fetchone()
    conn.close()
    
    if letter and letter[3]:  # 如果是公开的
        return render_template('letter.html', letter=letter)
    else:
        return "这封信是私密的", 403

if __name__ == '__main__':
    init_db()
    app.run(debug=True, host='0.0.0.0', port=5000)
